<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { DictApi } from '#/api';
import type { ItemTypeAPI } from '#/api/mes/md/itemtype';

import { reactive, ref, toRaw } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';
import { VxeButton } from '@vben/plugins/vxe-table';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { DictResp } from '#/api';
import { DeleteItemType, GetItemTypeList } from '#/api/mes/md/itemtype';
import Amend from '#/views/mes/md/itemtype/amend.vue';
// // 存储选中行的响应式变量
// const selectedRows = ref<ItemTypeAPI.Datum[]>([]);
const [AmendModal, amendModalApi] = useVbenModal({
  connectedComponent: Amend,
  destroyOnClose: true,
});
const sys_yes_no = reactive<DictApi.SelectOption[]>([]);
const mes_item_product = reactive<DictApi.SelectOption[]>([]);

DictResp(['sys_yes_no', 'mes_item_product']).then((res) => {
  if (res.mes_item_product) {
    mes_item_product.push(...res.mes_item_product);
  }
  if (res.sys_yes_no) {
    sys_yes_no.push(...res.sys_yes_no);
  }
});
const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  wrapperClass: 'grid-cols-2 gap-x-10 gap-y-4',
  schema: [
    {
      component: 'Input',
      fieldName: 'itemTypeId',
      dependencies: {
        triggerFields: ['itemTypeId'],
        show: false,
      },
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入分类名称',
        allowClear: true,
        class: 'mr-5',
      },
      fieldName: 'itemTypeName',
      label: '分类名称',
      labelClass: '  text-[#606266] font-bold',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: sys_yes_no,
        placeholder: '是否启用',
      },
      fieldName: 'enableFlag',
      label: '是否启用',
      labelClass: '  text-[#606266] font-bold',
    },
  ],

  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '搜索',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: [
      {
        align: 'center',
        field: 'itemTypeName',
        title: '分类',
        treeNode: true,
      },
      { type: 'seq', width: 70 },
      {
        field: 'itemOrProduct',
        title: '物料/产品',
        formatter: ({ cellValue }) => {
          const item = mes_item_product.find(
            (item) => item.value === cellValue,
          );
          return item?.label || '';
        },
      },
      {
        align: 'center',
        cellRender: { name: 'CellTag' },
        field: 'enableFlag',
        title: '是否启用',
      },
      {
        align: 'center',
        field: 'createTime',
        title: '创建时间',
      },
      {
        align: 'center',
        field: 'operation',
        fixed: 'right',
        slots: { default: 'action' },
        headerAlign: 'center',
        showOverflow: false,
        title: '操作',
        width: 200,
      },
    ],
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_params, formValues) => {
          const res = await GetItemTypeList({
            ...formValues,
          });
          itemTypeList.value = res.data;
          return { items: res.data, total: res.data.length };
        },
      },
    },

    rowConfig: {
      keyField: 'itemTypeId',
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      zoom: true,
    },
    treeConfig: {
      parentField: 'parentTypeId',
      rowField: 'itemTypeId',
      transform: true,
    },
  } as VxeTableGridOptions,
});
const expandAll = () => {
  gridApi.grid?.setAllTreeExpand(true);
};

const collapseAll = () => {
  gridApi.grid?.setAllTreeExpand(false);
};

function onActionClick({ code, row }: OnActionClickParams<ItemTypeAPI.Datum>) {
  switch (code) {
    case 'add': {
      onAppend(row);
      break;
    }
    case 'myDel': {
      onDelete(row);
      break;
    }
    case 'myEdit': {
      onEdit(row);
      break;
    }
    default: {
      break;
    }
  }
}
const itemTypeList = ref<ItemTypeAPI.Datum[]>([]);
function onRefresh() {
  gridApi.query();
}

function onEdit(row: ItemTypeAPI.Datum) {
  // console.log('编辑数据:', toRaw(row));
  const raw = toRaw(row);
  const parent = itemTypeList.value.find(
    (item) => item.itemTypeId === raw.parentTypeId,
  );

  const parentTypeName = parent ? parent.itemTypeName : raw.itemTypeName;

  amendModalApi.setData({ row: { ...raw, parentTypeName } }).open();
}

function onAppend(row: ItemTypeAPI.Datum) {
  amendModalApi.setData({ parentTypeId: row.itemTypeId }).open();
}

function onDelete(row: ItemTypeAPI.Datum) {
  const hideLoading = message.loading({
    content: `正在删除${row.itemTypeId}`,
    duration: 0,
    key: 'action_process_msg',
  });
  DeleteItemType(row.itemTypeId)
    .then(() => {
      message.success({
        content: `删除${row.itemTypeId}成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
</script>
<template>
  <Page auto-content-height>
    <AmendModal @success="onRefresh" class="w-[600px]" />
    <Grid>
      <template #toolbar-tools>
        <VxeButton
          class="mx-2"
          status="primary"
          icon="vxe-icon-arrow-down"
          @click="expandAll"
        >
          展开全部
        </VxeButton>
        <VxeButton
          status="primary"
          icon="vxe-icon-arrow-right"
          @click="collapseAll"
        >
          折叠全部
        </VxeButton>
      </template>
      <template #action="{ row }">
        <VxeButton
          mode="text"
          icon="vxe-icon-signature"
          @click="onActionClick({ code: 'myEdit', row })"
          status="primary"
        >
          修改
        </VxeButton>
        <VxeButton
          mode="text"
          icon="vxe-icon-add"
          @click="onActionClick({ code: 'add', row })"
          status="warning"
        >
          新增
        </VxeButton>
        <VxeButton
          v-if="row.machineryTypeId !== 1"
          icon="vxe-icon-delete"
          mode="text"
          @click="onActionClick({ code: 'myDel', row })"
          status="error"
        >
          删除
        </VxeButton>
      </template>
    </Grid>
  </Page>
</template>
<style lang="scss" scoped>
.menu-badge {
  top: 50%;
  right: 0;
  transform: translateY(-50%);

  & > :deep(div) {
    padding-top: 0;
    padding-bottom: 0;
  }
}
</style>
